package main

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

func main() {
	//连接数据库查询
	db, err := sql.Open("mysql", "root:123456@tcp(39.108.187.254:3306)/tornado")
	if err != nil {
		log.Fatal(err.Error())
	}
	//最终关闭数据库
	defer db.Close()
	msql := "select * from student"
	rows, err := db.Query(msql)
	if err != nil {
		log.Fatal(err.Error())
	}
	//获取列名
	columns, _ := rows.Columns()
	//定义一个切片,长度是字段的个数,切片里面的元素类型是sql.RawBytes
	values := make([]sql.RawBytes, len(columns))
	//定义一个切片,元素类型是interface{} 接口
	scanArgs := make([]interface{}, len(values))
	for i := range values {
		//把sql.RawBytes类型的地址存进去了
		scanArgs[i] = &values[i]
	}
	//获取字段值
	var result []map[string]string
	for rows.Next() {
		res := make(map[string]string)
		rows.Scan(scanArgs...)
		for i, col := range values {
			res[columns[i]] = string(col)
		}
		result = append(result, res)
	}
	//遍历结果
	for _, r := range result {
		for k, v := range r {
			log.Printf("%s==%s", k, v)
		}
	}
	rows.Close()
}
